class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int len = prices.size();
        vector<vector<int>> f(len + 1, vector<int>(3, -0x3f3f3f3f));
        auto g = f;
        f[0][0] = -prices[0];
        g[0][0] = 0;
        for (int i = 1; i < len; i++) {
            for (int j = 0; j < 3; j++) {
                f[i][j] = max(f[i - 1][j], g[i - 1][j] - prices[i]);
                g[i][j] = g[i - 1][j];
                if (j >= 1) {
                    g[i][j] = max(g[i][j], f[i - 1][j - 1] + prices[i]);
                }
            }
        }
        int ret = 0;
        for (int j = 0; j < 3; j++) {
            // cout<<g[len-1][j]<<" "<<ret<<" ";
            ret = max(ret, g[len - 1][j]);
        }
        return ret;
    }
};